import React, {useState, useEffect, useContext} from 'react';

import {LedgerContext} from '../../Ledger';

export default ({hidden, tableName, displayName}) => {

  const [status, setStatus] = useState('DONE');

  const {evalBook} = useContext(LedgerContext);

  useEffect(() => {
    if(status === 'UPDATE'){
      (async() => {
        try {
          evalBook(tableName);
          setStatus('DONE');
        } catch (err) {
          console.error(err);
          setStatus('DEAD');
        }
      })();
    }
  }, [status])

  const update = () => {
    setStatus('UPDATE');
  }

  const elem = hidden
  ? <div key="update"></div>
  : <button key="update" className="button" onClick={() => update()}>{displayName}</button>

  return [elem]
}
